package com.tjp.eight.ui.fragment.setting;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tjp.eight.LoginEvent;
import com.tjp.eight.R;
import com.tjp.eight.ResultModel;
import com.tjp.eight.RxBus;
import com.tjp.eight.WApplication;
import com.tjp.eight.ui.fragment.BaseFragment;
import com.tjp.eight.ui.fragment.loginreg.ActivityLogin;
import com.tjp.eight.utils.ActivityUtils;
import com.tjp.eight.utils.AppUtils;
import com.tjp.eight.utils.ApplicationUtil;
import com.tjp.eight.utils.DataCleanUtils;
import com.tjp.eight.utils.SharePreferencesUtils;
import com.tjp.eight.utils.StringUtils;
import com.tjp.eight.utils.ToatUtils;
import com.tjp.eight.utils.UpdateService;
import com.tjp.eight.views.CustomDialog;
import com.tjp.eight.views.DialogLogin;
import com.tjp.eight.views.LogoutDailog;
import com.tjp.eight.views.ShareDialog;

import org.w3c.dom.Text;

import java.io.File;


/**
 * Created by Administrator on 2017/3/1.
 */
public class FragmentSetting extends BaseFragment<SettingPresenter> implements SettingView {
    private TextView tv_login;
    private TextView tv_cache;
    private TextView tv_version;
    private RelativeLayout rl_help;
    private RelativeLayout rl_clear_cache;
    private RelativeLayout rl_check_new;
    private RelativeLayout ll_about_us;
    private RelativeLayout rl_to_share;
    private RelativeLayout rl_to_support;
    private RelativeLayout rl_rock;
    private LogoutDailog logoutDailog;
    private DialogLogin dialogLogin;

    private TextView tvSmall;
    private TextView tvNormal;
    private TextView tvLarge;

    private ShareDialog shareDialog;
    private int currentShareType = -1;

    @Override
    protected SettingPresenter createPresenter() {
        return new SettingPresenter(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = super.onCreateView(inflater, container, savedInstanceState);
        if (contentView == null) {
            contentView = inflater.inflate(R.layout.fragment_setting, container, false);
        }
        initView();
        return contentView;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 0x01:
                loginSuccess();
                break;
        }
    }

    void loginSuccess() {
        tv_login.setText("退出登录");
    }

    void resetTV() {
        tvSmall.setSelected(false);
        tvNormal.setSelected(false);
        tvLarge.setSelected(false);
    }

    View.OnClickListener tvClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_small:
                    resetTV();
                    tvSmall.setSelected(true);
                    SharePreferencesUtils.setWebTextSize(2);
                    break;
                case R.id.tv_normal:
                    resetTV();
                    tvNormal.setSelected(true);
                    SharePreferencesUtils.setWebTextSize(3);
                    break;
                case R.id.tv_big:
                    resetTV();
                    tvLarge.setSelected(true);
                    SharePreferencesUtils.setWebTextSize(4);
                    break;
            }
        }
    };

    void initView() {
        tvSmall = (TextView) contentView.findViewById(R.id.tv_small);
        tvNormal = (TextView) contentView.findViewById(R.id.tv_normal);
        tvLarge = (TextView) contentView.findViewById(R.id.tv_big);

        switch (SharePreferencesUtils.geWebTextSize()) {
            case 2:
                resetTV();
                tvSmall.setSelected(true);
                break;
            case 3:
                resetTV();
                tvNormal.setSelected(true);
                break;
            case 4:
                resetTV();
                tvLarge.setSelected(true);
                break;
            default:
                resetTV();
                tvNormal.setSelected(true);
                break;
        }

        tvSmall.setOnClickListener(tvClick);
        tvNormal.setOnClickListener(tvClick);
        tvLarge.setOnClickListener(tvClick);

        tv_login = (TextView) contentView.findViewById(R.id.tv_login);
        tv_cache = (TextView) contentView.findViewById(R.id.tv_cache);
        tv_version = (TextView) contentView.findViewById(R.id.tv_version);
        if (!StringUtils.isNullOrEmpty(ApplicationUtil.getVerName(ApplicationUtil.getApplicationContext()))) {
            tv_version.setText("当前版本：" + "v" + ApplicationUtil.getVerName(ApplicationUtil.getApplicationContext()) + "."
                    + ApplicationUtil.getVerCode(ApplicationUtil.getApplicationContext()));
        }
        try {
            String cacheSize = DataCleanUtils.getCacheSizes(WApplication.getInstance().getCacheDir());
            tv_cache.setText("当前缓存：" + cacheSize);
        } catch (Exception e) {
            e.printStackTrace();
        }
        tv_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("登录".equals(tv_login.getText().toString())) {
                    Intent intent = new Intent(getActivity(), ActivityLogin.class);
                    startActivityForResult(intent, 0x01);
                } else if ("退出登录".equals(tv_login.getText().toString())) {
                    showDialog();
                }
            }
        });
        if (StringUtils.isNullOrEmpty(SharePreferencesUtils.getUid())) {
            tv_login.setText("登录");
        } else {
            tv_login.setText("退出登录");
        }
        rl_help = (RelativeLayout) contentView.findViewById(R.id.rl_help);
        rl_clear_cache = (RelativeLayout) contentView.findViewById(R.id.rl_clear_cache);
        rl_check_new = (RelativeLayout) contentView.findViewById(R.id.rl_check_new);
        ll_about_us = (RelativeLayout) contentView.findViewById(R.id.ll_about_us);
        rl_to_share = (RelativeLayout) contentView.findViewById(R.id.rl_to_share);
        rl_to_support = (RelativeLayout) contentView.findViewById(R.id.rl_to_support);
        rl_rock = (RelativeLayout) contentView.findViewById(R.id.rl_rock);
        rl_rock.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!SharePreferencesUtils.isLogin()) {
                    Intent intent = new Intent(getActivity(), ActivityLogin.class);
                    startActivityForResult(intent, 0x01);
                } else
                    ActivityUtils.startRock(getActivity());
            }
        });
        rl_to_support.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppUtils.goToMarket(getActivity(), WApplication.getInstance().getPackageName());
            }
        });
        rl_to_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShare();
            }
        });
        ll_about_us.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.startAboutUs(getActivity());
            }
        });
        rl_check_new.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDialogLoad();
                presenter.checknew(getPJson());
            }
        });
        rl_help.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ActivityUtils.startHelp(getActivity());
            }
        });
        rl_clear_cache.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final CustomDialog customDialog = new CustomDialog(getActivity());
                customDialog.setMessage("确定要清除缓存吗？");
                customDialog.setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DataCleanUtils.cleanInternalCache(WApplication.getInstance());
                        DataCleanUtils.cleanDatabases(WApplication.getInstance());
                        DataCleanUtils.deleteFilesByDirectory(new File("/sdcard/八秒视频_temp/"));
                        DataCleanUtils.deleteFilesByDirectory(new File("/sdcard/八秒视频/"));
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (getContext() != null)
                                    Toast.makeText(getContext(), "清除成功", Toast.LENGTH_SHORT).show();
                                try {
                                    String cacheSize = DataCleanUtils.getCacheSizes(WApplication.getInstance().getCacheDir());
                                    if (tv_cache != null)
                                        tv_cache.setText("当前缓存：" + cacheSize);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }, 2000);
                        customDialog.dismiss();
                    }
                });
                customDialog.setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        customDialog.dismiss();
                    }
                });
                customDialog.show();
            }
        });
    }

    void showShare() {
        if (shareDialog == null) {
            shareDialog = new ShareDialog(getContext());
        }
        shareDialog.setOnClickType(new ShareDialog.OnClickType() {
            @Override
            public void clickType(int type) {
                currentShareType = type;
                switch (type) {
                    case ShareDialog.TYPE_WX:
                        break;
                    case ShareDialog.TYPE_WX_CIRCLE:
                        break;
                    case ShareDialog.TYPE_QQ:
                        break;
                    case ShareDialog.TYPE_QQ_ZONE:
                        break;
                    case ShareDialog.TYPE_COLLECTION:
                        break;
                    case ShareDialog.TYPE_REPORT:
                        break;
                    case ShareDialog.TYPE_DISMISS:
                        dismissShare();
                        break;
                }
            }
        });
        shareDialog.setRCVisible(View.INVISIBLE);
        shareDialog.show();
    }

    void dismissShare() {
        if (shareDialog != null) {
            shareDialog.dismiss();
        }
    }

    void showDialog() {
        if (logoutDailog == null) {
            logoutDailog = new LogoutDailog(getActivity());
            logoutDailog.setLogoutInterface(new LogoutDailog.LogoutInterface() {
                @Override
                public void logout() {
                    SharePreferencesUtils.logout();
                    LoginEvent loginEvent = LoginEvent.getLoginEvent();
                    loginEvent.login = false;
                    loginEvent.logout = true;
                    RxBus.getInstance().post(loginEvent);
                    tv_login.setText("登录");
                    logoutDailog.dismiss();
                }
            });
        }
        logoutDailog.show();
    }

    private String getPJson() {
        return "{}";
    }

    @Override
    public void checkSuccess(final CheckResultModel model) {
        dismissDialogLoad();
        if (model != null) {
            if (!ApplicationUtil.getV().equals(model.v)
                    && !StringUtils.isNullOrEmpty(model.v)
                    && !StringUtils.isNullOrEmpty(model.apk_path)) {
                final CustomDialog customDialog = new CustomDialog(getActivity());
                customDialog.setMessage("是否要下载最新版本！");
                customDialog.setPositiveButton("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), UpdateService.class);
                        intent.putExtra("url", model.apk_path);
                        intent.putExtra("filename", "八秒视频.apk");
                        getActivity().startService(intent);
                        customDialog.dismiss();
                    }
                });
                customDialog.setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        customDialog.dismiss();
                    }
                });
                customDialog.show();
            } else {
                ToatUtils.toastSuccess(getActivity(), "您当前的版本已是最新版本");
            }
        }
    }

    @Override
    public void fail(String msg) {
        dismissDialogLoad();
    }

    void showDialogLoad() {
        if (dialogLogin == null) {
            dialogLogin = new DialogLogin(getActivity());
            dialogLogin.setTv_tips("检测版本");
            dialogLogin.setTv_tips_titls("努力加载中...");
        }
        dialogLogin.show();
    }

    void dismissDialogLoad() {
        if (dialogLogin == null) {
            dialogLogin = new DialogLogin(getActivity());
        }
        dialogLogin.dismiss();
    }
}
